package com.ciei.dpagm.handler;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ciei.dpagm.util.APP;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局返回值处理器
 * @author 方诺舟
 * @date 2020/07/28
 */
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 强制对所有返回值启用
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o == null) {
            return new JSONObject();
        }
        // 处理IPage类型的返回值
        if (o instanceof IPage) {
            IPage pageData = (IPage)o;
            JSONObject json = new JSONObject();
            json.put(APP.DATA, pageData.getRecords());
            json.put(APP.TOTAL_COUNT, pageData.getTotal());
            json.put(APP.CURRENT_PAGE, pageData.getCurrent());
            return json;
        }

        return o;
    }
}
